// im-select-win.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include <string>
#include <Windows.h>

using namespace std;

int getInputMethod(uint64_t winID) {
    HWND hwnd = reinterpret_cast<HWND>(winID);
    if (hwnd) {
        DWORD threadID = GetWindowThreadProcessId(hwnd, NULL);
        HKL currentLayout = GetKeyboardLayout(threadID);
        uint64_t x = reinterpret_cast<uint64_t>(currentLayout) & 0x0000FFFF;
        return ((int)x);
    }
    return 0;
}

void switchInputMethod(uint64_t winID, int locale) {
    HWND hwnd = reinterpret_cast<HWND>(winID);
    LPARAM currentLayout = ((LPARAM)locale);
    PostMessage(hwnd, WM_INPUTLANGCHANGEREQUEST, 0, currentLayout);
}

uint64_t getInputWindow() {
    HWND hwnd = GetForegroundWindow();
    uint64_t x = reinterpret_cast<uint64_t>(hwnd);
    return x;
}

int main(int argc, char** argv)
{
    if (argc == 1) {
        uint64_t winID = getInputWindow();
        cout << winID;
    }
    else if (argc == 2) {
        uint64_t winID = stoull(argv[1]);
        int imID = getInputMethod(winID);
        cout << imID << endl;
    }
    else {
        uint64_t winID = stoull(argv[1]);
        int locale = atoi(argv[2]);
        switchInputMethod(winID, locale);
    }
    return 0;
}
